//
//  EMAgreementViewController.m
//  EasyMoney
//
//  Created by 邓乐 on 2020/1/12.
//  Copyright © 2020 zh. All rights reserved.
//

#import "EMAgreementViewController.h"
#import "EMNavBarView.h"
#import <WebKit/WebKit.h>
#import "EMAgreementBottomView.h"
#import "EMAgreementsRequestModel.h"
#import "EMAgreementsResponseModel.h"

@interface EMAgreementViewController ()<WKNavigationDelegate>

@property (nonatomic, strong) EMNavBarView *nav;
@property (nonatomic, strong) UIButton *retryBtn;
@property (nonatomic, strong) WKWebView *webview;
@property (nonatomic, strong) EMAgreementBottomView *bottom;

@end

@implementation EMAgreementViewController

+ (BOOL)isSingleton
{
    return YES;
}

+ (BOOL)shouldPresent
{
    return YES;
}

+ (BOOL)shouldDimiss
{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self requestAgreementURL];
}

- (void)setupUI
{
    //1. header
    _nav = [[EMNavBarView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, EMNavBarHeight)];
    _nav.title = NSLocalizedString(@"隐私政策全文", nil);
    [self.view addSubview:_nav];
    
    //2. webview
    CGFloat tabBarHeight = EMNavBarHeight == 44 ? 34 : 49;
    CGFloat bottomHeight = 90+tabBarHeight;
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
    
    _webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, EMNavBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-EMNavBarHeight-bottomHeight) configuration:config];
    _webview.backgroundColor = ColorFromRGB(0xf8f8f8);
    _webview.navigationDelegate = self;
    
    [self.view addSubview:_webview];
    
    //bottom
    _bottom = [[EMAgreementBottomView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_webview.frame), SCREEN_WIDTH, bottomHeight)];
    [self.view addSubview:_bottom];
    [_bottom.checkboxView.checkboxBtn addTarget:self action:@selector(clickCheckbox:) forControlEvents:UIControlEventTouchUpInside];
    [_bottom.btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    _bottom.userInteractionEnabled = YES;
    
    _retryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _retryBtn.titleLabel.font = FONT_PINGFANG_MEDIUM_(16);
    _retryBtn.layer.cornerRadius = 22;
    _retryBtn.layer.masksToBounds = YES;
    [self.view addSubview:_retryBtn];
    UIImage *image = [UIImage gradientImageSize:CGSizeMake(SCREEN_WIDTH-48-48, 44) colors:@[[UIColor colorwithHexString:@"#36B2FF"],[UIColor colorwithHexString:@"#2F5AFF"]] startPoint:CGPointMake(0, 22) endPoint:CGPointMake(SCREEN_WIDTH-48-48, 22)];
    [_retryBtn setBackgroundImage:image forState:UIControlStateNormal];
    [_retryBtn setTitle:NSLocalizedString(@"重试", nil) forState:UIControlStateNormal];
    [_retryBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_retryBtn setEnabled:YES];
    [_retryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_webview);
        make.left.equalTo(_webview).offset(30);
        make.right.equalTo(_webview).offset(-30);
        make.height.mas_equalTo(44);
    }];
    [_retryBtn addTarget:self action:@selector(clickRetryBtn:) forControlEvents:UIControlEventTouchUpInside];
    _retryBtn.hidden = YES;
}

+ (BOOL)needShowAgreement
{
    return ![[NSUserDefaults standardUserDefaults] boolForKey:kEMAcceptAgreement];
}

- (void)clickBtn:(UIButton *)sender
{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kEMAcceptAgreement];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickCheckbox:(UIButton *)sender
{
    _bottom.checkboxView.checkbox.highlighted = !_bottom.checkboxView.checkbox.highlighted;
    [_bottom.btn setEnabled:_bottom.checkboxView.checkbox.highlighted];
}

- (void)clickRetryBtn:(UIButton *)sender
{
    [self requestAgreementURL];
}

- (void)requestAgreementURL{
    _retryBtn.hidden = YES;
    [SVProgressHUD showWithStatus:@"加载中"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    EMAgreementsRequestModel *request = [[EMAgreementsRequestModel alloc]init];
    request.type = @"secret";
    __weak typeof(self)weakSelf = self;
    [request requestSuccess:^(EMAgreementsResponseModel *response, NSString * _Nonnull message) {
        NSURL *url = [NSURL URLWithString:[[response.agreements firstObject]url]];
        [self.webview loadRequest:[NSURLRequest requestWithURL:url]];
    } failure:^(NSInteger errorCode, NSString * _Nonnull errorMessage, NSError * _Nonnull error) {
        [weakSelf showResult:NO];
    }];
}

- (void)showResult:(BOOL)result
{
    [SVProgressHUD dismiss];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    self.retryBtn.hidden = result;
    self.bottom.userInteractionEnabled = result;
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    [self showResult:NO];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable title, NSError * _Nullable error) {
        if (SAFE_STRING(title).length > 0) {
            self.nav.title = title;
        }
    }];
    [self showResult:YES];
}

@end
